#!/bin/bash
# SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
# SPDX-License-Identifier: MIT

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
IMAGE_NAME="uos-syslog-ng-exporter"
VERSION=${1:-"latest"}
REGISTRY=${2:-""}
FULL_IMAGE_NAME="${REGISTRY:+$REGISTRY/}${IMAGE_NAME}:${VERSION}"

# 打印函数
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查Docker是否安装
check_docker() {
    if ! command -v docker &> /dev/null; then
        print_error "Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    if ! docker info &> /dev/null; then
        print_error "Docker 服务未运行，请启动 Docker 服务"
        exit 1
    fi
}

# 构建Docker镜像
build_image() {
    print_info "开始构建 Docker 镜像..."
    print_info "镜像名称: $FULL_IMAGE_NAME"
    
    # 检查是否存在 Dockerfile
    if [ ! -f "Dockerfile" ]; then
        print_error "Dockerfile 不存在"
        exit 1
    fi
    
    # 构建镜像
    if docker build -t "$FULL_IMAGE_NAME" .; then
        print_success "Docker 镜像构建成功: $FULL_IMAGE_NAME"
    else
        print_error "Docker 镜像构建失败"
        exit 1
    fi
}

# 推送镜像到仓库
push_image() {
    if [ -n "$REGISTRY" ]; then
        print_info "推送镜像到仓库: $REGISTRY"
        
        if docker push "$FULL_IMAGE_NAME"; then
            print_success "镜像推送成功: $FULL_IMAGE_NAME"
        else
            print_error "镜像推送失败"
            exit 1
        fi
    else
        print_info "未指定仓库，跳过推送"
    fi
}

# 显示镜像信息
show_image_info() {
    print_info "镜像信息:"
    docker images "$IMAGE_NAME" --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}\t{{.CreatedAt}}"
}

# 主函数
main() {
    print_info "UOS Syslog-NG Exporter Docker 构建脚本"
    print_info "=========================================="
    
    # 检查Docker环境
    check_docker
    
    # 构建镜像
    build_image
    
    # 推送镜像
    push_image
    
    # 显示镜像信息
    show_image_info
    
    print_success "构建完成！"
    print_info "运行容器: docker run -p 9309:9309 $FULL_IMAGE_NAME"
}

# 执行主函数
main "$@"
